import 'package:call_phone_test/page/login.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

class HomePage extends StatefulWidget {
  const HomePage({Key? key}) : super(key: key);

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {

  static const methodChannel = MethodChannel('com.sz.callPhoneTest.call_phone_test');
  int connectState = 0;
  bool isLogouting = false;

  @override
  void initState() {
    super.initState();
    methodChannel.setMethodCallHandler(_methodChannelHandler);
    _getConnectState();
  }

  @override
  void dispose() {
    super.dispose();
  }


  void _getConnectState() async {
    int state = await methodChannel.invokeMethod('getConnectState');
    setState(() {
      connectState = state;
    });
    print('_getConnectState() -> connectState=${state}');
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
          title: const Text('软电话', style: TextStyle(fontSize: 16)),
          centerTitle: true,
          automaticallyImplyLeading: false,
      ),
      body: WillPopScope(
        onWillPop: () async {
          return true;
        },
        child: Container(
          alignment: Alignment.center,
          padding: const EdgeInsets.symmetric(horizontal: 18),
          child: Column(
            children: [
              Expanded(flex: 1, child: Container()),

              Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  const Text('连接状态: ', style: TextStyle(fontSize: 18, color: Colors.black)),

                  if (connectState == 1)
                    const Text('连接中...', style: TextStyle(fontSize: 18, color: Colors.red, fontWeight: FontWeight.bold))
                  else if (connectState == 2)
                    const Text('已连接', style: TextStyle(fontSize: 18, color: Colors.blue, fontWeight: FontWeight.bold))
                  else if (connectState == 3)
                      const Text('未连接', style: TextStyle(fontSize: 18, color: Colors.grey, fontWeight: FontWeight.bold)),

                  const SizedBox(width: 30),

                  GestureDetector(
                    onTap: _logout,
                    child: Container(
                      alignment: Alignment.center,
                      width: 100,
                      height: 35,
                      child: const Text('注销', style: TextStyle(fontSize: 18, color: Colors.black, fontWeight: FontWeight.bold)),
                      decoration: BoxDecoration(
                        borderRadius: const BorderRadius.all(Radius.circular(14.0)),
                        border: Border.all(width: 1, color: Colors.grey),
                      ),
                    ),
                  )
                ],
              ),

              const SizedBox(height: 20),

              Row(
                children: [
                  Expanded(flex: 1, child: Container()),
                  GestureDetector(
                    onTap: () async {
                      int result = await methodChannel.invokeMethod('callphone', {'name': "test"});
                      if (result == 200) {
                      }
                    },
                    child: Container(
                      alignment: Alignment.center,
                      width: 100,
                      height: 35,
                      child: const Text('拨打', style: TextStyle(fontSize: 18, color: Colors.black, fontWeight: FontWeight.bold)),
                      decoration: BoxDecoration(
                        borderRadius: const BorderRadius.all(Radius.circular(14.0)),
                        border: Border.all(width: 1, color: Colors.grey),
                      ),
                    ),
                  ),
                  const SizedBox(width: 20),
                  GestureDetector(
                    onTap: () async {
                      int result = await methodChannel.invokeMethod('hangup', {'name': "test"});
                      if (result == 200) {
                      }
                    },
                    child: Container(
                      alignment: Alignment.center,
                      width: 100,
                      height: 35,
                      child: const Text('挂断', style: TextStyle(fontSize: 18, color: Colors.black, fontWeight: FontWeight.bold)),
                      decoration: BoxDecoration(
                        borderRadius: const BorderRadius.all(Radius.circular(14.0)),
                        border: Border.all(width: 1, color: Colors.grey),
                      ),
                    ),
                  ),
                  Expanded(flex: 1, child: Container()),
                ],
              ),

              const SizedBox(height: 20),

              // Row(
              //   children: [
              //     Expanded(flex: 1, child: Container()),
              //     GestureDetector(
              //       onTap: () async {
              //         int result = await methodChannel.invokeMethod('startRecording', {'name': "test"});
              //         if (result == 200) {
              //         }
              //       },
              //       child: Container(
              //         alignment: Alignment.center,
              //         width: 100,
              //         height: 35,
              //         child: const Text('开始录音', style: TextStyle(fontSize: 18, color: Colors.black, fontWeight: FontWeight.bold)),
              //         decoration: BoxDecoration(
              //           borderRadius: const BorderRadius.all(Radius.circular(14.0)),
              //           border: Border.all(width: 1, color: Colors.grey),
              //         ),
              //       ),
              //     ),
              //     const SizedBox(width: 20),
              //     GestureDetector(
              //       onTap: () async {
              //         int result = await methodChannel.invokeMethod('stopRecording', {'name': "test"});
              //         if (result == 200) {
              //         }
              //       },
              //       child: Container(
              //         alignment: Alignment.center,
              //         width: 100,
              //         height: 35,
              //         child: const Text('停止录音', style: TextStyle(fontSize: 18, color: Colors.black, fontWeight: FontWeight.bold)),
              //         decoration: BoxDecoration(
              //           borderRadius: const BorderRadius.all(Radius.circular(14.0)),
              //           border: Border.all(width: 1, color: Colors.grey),
              //         ),
              //       ),
              //     ),
              //     Expanded(flex: 1, child: Container()),
              //   ],
              // ),

              Expanded(flex: 1, child: Container()),
            ],
          ),
        ),
      ),
    );
  }

  void _logout() async {
    if (isLogouting) {
      return;
    }
    isLogouting = true;
    try{
      int result = await methodChannel.invokeMethod('logout', {'name': "test"});
      if (result == 200) {
        isLogouting = false;
        Navigator.pushReplacement(context,
          MaterialPageRoute(
              builder: (context) {
                return LoginPage();
              }),
        );
      }
    }catch(e){
      isLogouting = false;
    }

  }

  //安卓原生调用flutter, 方法是异步的
  Future<String> _methodChannelHandler(MethodCall call) async {
    String result = "";
    switch (call.method) {
      case "onWebSocketStateListener":
        int state = call.arguments?? 3;
        print('onWebSocketStateListener() -> state=$state');
        setState(() {
          connectState = state;
        });
        break;
    }
    return result;
  }

}
